import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:get/get.dart';

import '../values/values.dart';
import 'services.dart';

class ConfigStore extends GetxController {
  static ConfigStore get to => Get.find();

  bool isFirstOpen = false;

  bool get isRelease => const bool.fromEnvironment("dart.vm.product");
  late Locale locale;
  Locale fallbackLocale = const Locale('en', 'US');
  List<Locale> languages = [
    const Locale('en', 'US'),
    const Locale('zh', 'CN'),
    const Locale('th', 'TH'),
  ];

  String get countryCode => dotenv.env['COUNTRY_CODE'] ?? '60';
  String get currency => dotenv.env['CURRENCY'] ?? 'RM';

  Map<String, String> get webUrls => {
        'Privacy policy': 'https://oss.mowanka.com/h5/agreement/PrivacyPolicy_en.html',
        'Terms of service': 'https://oss.mowanka.com/h5/agreement/PrivacyPolicy_en.html',
        'Case of DuitNow': 'https://oss.mowanka.com/h5/agreement/PrivacyPolicy_en.html',
      };

  void onInitLocale() {
    // 确保locale不为空且是在语言列表中
    locale = Get.deviceLocale ?? fallbackLocale;
    var index = languages.indexWhere((element) {
      return element.languageCode == locale.languageCode;
    });
    if (index >= 0) {
      locale = languages[index];
    }
    // 读取上次保存的语言
    var langCode = StorageService.to.getString(STORAGE_LANGUAGE_CODE);
    if (langCode.isEmpty) return;
    index = languages.indexWhere((element) {
      return element.languageCode == langCode;
    });
    if (index < 0) return;
    locale = languages[index];
  }

  void onLocaleUpdate(Locale value) {
    locale = value;
    Get.updateLocale(value);
    StorageService.to.setString(STORAGE_LANGUAGE_CODE, value.languageCode);
  }

  @override
  void onInit() {
    super.onInit();
    onInitLocale();
  }
}
